package service

import (
	"time"

	"example.com/m/v2/model/mysql"
	"example.com/m/v2/types"
	"gorm.io/gorm"
)

type Image struct {
	BaseService
	db *gorm.DB
}

func NewImage(svcCtx *ServiceContext, db *gorm.DB) *Image {
	res := Image{db: db, BaseService: BaseService{svcCtx: svcCtx}}
	return &res
}

func (i *Image) GetById(id int64) *mysql.Image {
	var image mysql.Image
	i.db.Where("id=?", id).First(&image)
	return &image
}

func (i *Image) Create(req *types.AddImageReq, userId int64) *mysql.Image {
	image := mysql.Image{
		UserId:      userId,
		Width:       req.Width,
		Height:      req.Height,
		Url:         req.Url,
		CreatedTime: time.Now(),
	}
	i.db.Create(&image)
	return &image
}

func (i *Image) GetListByPage(req *types.UserImageReq, userId int64) (*[]mysql.Image, int64) {
	var res *[]mysql.Image
	var total int64
	query := i.db.Where("status=?", 1).Where("user_id=?", userId).Order("id desc")

	page := 1
	if req.Page != 0 {
		page = req.Page
	}

	pageSize := 20
	if req.PageSize != 0 {
		pageSize = req.PageSize
	}
	query.Count(&total)
	query.Offset(pageSize * (page - 1)).Limit(pageSize).Find(&res)
	return res, total
}

func (p *Image) Delete(req *types.ImageDelReq) {
	p.db.Model(&mysql.Image{}).Where("id=?", req.Id).Update("status", 0).Update("updated_time", time.Now())
}
